﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Data;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using Meraz.Core.Helpers;
using Meraz.Core.Parsers;
using Meraz.Core.Factories;
using Ninject;

namespace Meraz.Core.Commands
{
    public interface IParsePostCommand
    {
        IObjectFactory ObjectFactory { get; set; }
        IBlogRepository BlogRepository { get; set; }
        INetworkHelper NetworkHelper { get; set; }
        PostValues Execute(string permalink);
    }
    /// <summary>
    /// 	ParsePostCommand
	///	parse Post into constituent parts
	///	Post Attributes and Body
	///	Aliases
	///	Urls

    /// </summary>
    public class ParsePostCommand : BaseCommand, IParsePostCommand
    {
        [Inject]
        public ParsePostCommand(IObjectFactory objectFactory, IBlogRepository blogRepo, INetworkHelper networkHelper)
        {
            this.ObjectFactory = objectFactory ?? new ObjectFactory();
            this.BlogRepository = blogRepo ?? new BlogRepository();
            this.NetworkHelper = networkHelper ?? new NetworkHelper();
        }
        public IObjectFactory ObjectFactory { get; set; }
        public IBlogRepository BlogRepository { get; set; }
        public INetworkHelper NetworkHelper { get; set; }
        public PostValues Execute(string permalink)
        {
            Blog blog = BlogRepository.GetByUrl(permalink);
            BlogKeyType blogKeyType;
            if (blog == null)
            {
                blogKeyType = BlogKeyType.Unknown;
            }
            else
                blogKeyType = blog.BlogKeyType;
            IBlogParser parser = ObjectFactory.GetBlogParser(blogKeyType);
            string source = NetworkHelper.Download(permalink);
            PostValues post = parser.Parse(permalink, source);
            post.Permalink = permalink;
            return post;
        }
    }
}
